/**
 * 路径配置
 */
var urlConfig = {
	getFunctionQuery : baseUrl + "function/getFunctionQuery",// 获取用户信息
	getParentName : baseUrl + "function/getParentName", // 查出父节点名称作为下拉列表
	getFunctionK : baseUrl + "function/getFunctionK", // K校验不能重复
	addFunction : baseUrl + "function/addFunction", // 添加
	updateFunction : baseUrl + "function/updateFunction", // 修改
	deleteFunction : baseUrl + "function/deleteFunction", // 删除configUser
}
var table_row_num = 10;// 表格显示行数
/**
 * 表格渲染
 */
$(document).ready(function() {
	initOptions1();
	createTable();
})

// 创建主要表格
function createTable() {
	$.ajax({
		url : urlConfig.getFunctionQuery,
		type : 'post',
		data : {
			type : 1
		},
		async : true, // 默认为true 异步 \
		dataType : "json",
		error : function() {
			console.info('error');
		},
		success : function(data) {

			var tableData = data.data;
			showTable(tableData);
		}
	})
}

function showTable(tableData) {
	maintable = $('#am_tab').DataTable({
		destroy : true,
		// paging: false, //禁用分页
		ordering : false,
		bAutoWidth : false,
		info : false,// 禁用显示条目
		searching : false,
		filter : false,// 搜索框禁用
		lengthChange : false, // 显示条目禁用
		displayLength : table_row_num, // 显示条目
		"data" : tableData,
		"order" : [ [ 1, 'asc' ] ],
		// 下拉按钮激活(重绘的回调函数 )
		"drawCallback" : function(settings, json) {
			// 给表格添加行号
			var api = this.api();
			var rows = api.rows({ page : 'current' }).nodes();
			var rowsData = api.rows({ page : 'current' }).data();
			var last = null;
			api.column(1, {
				page : 'current'}).data().each(
					function(group, i) {
						if (last !== group) {
							$(rows).eq(i).before(
								'<tr class="group">'
									+ '<td>'
									+ "<span  style='cursor:pointer;color:#F37B1D' >"
									+ group
									+ "</span>"
									+ '</td>'
									+ '<td>'
									+ ""
									+ '</td>'
									+ '<td class="am-text-center">'
									+ rowsData[i].functionParentK
									+ '</td>'
									+ '<td>'
									+ ""
									+ '</td>'
									+ "<td class='am-text-center'>"
									+ '<div class="am-btn-toolbar">'
									+ ' <div class="am-btn-group am-btn-group-xs">'
									+ '  <button  class="am-btn am-btn-default am-btn-xs am-text-secondary" onclick="showModal(\''
									+ rowsData[i].parentId
									+ '\')"><span class="am-icon-pencil-square-o"></span> 修改</button>'
									+ ' <button  class="am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only" onclick="showConfirm(\''
									+ rowsData[i].parentId
									+ '\')" ><span class="am-icon-trash-o"></span> 删除</button>'
									+ ' </div>'
									+ ' </div>'
									+ "</td>"
									+ '</tr>');
							last = group;
						}
					}
				);
				$('.am-dropdown').dropdown({
					justify : '#doc-dropdown-justify-js'
				});
		},
		columns : [ {
			"data" : "functionName",
			"className" : "content_title",
			"orderable" : false
		}, {
			"data" : "functionParentName",
			sClass : "am-text-center"
		}, {
			"data" : "k",
			width : "auto",
			sClass : "am-text-center"
		}, {
			"data" : "functionUrl",
			width : "auto",
			sClass : "am-text-center"
		}, {
			"orderable" : false,
			"data" : null,
			"width" : "auto",
			"defaultContent" : '',
			sClass : "am-text-center"
		} ],
		"columnDefs" : [
				{
					targets : 0,
					"render" : function(data, type, full) {
						return '<span style="cursor:pointer;color:#0E90D2" >'
								+ "&nbsp;&nbsp;&nbsp;&nbsp;"
								+ data + '</span>';
					}
				},
				{

					targets : 4,
					"render" : function(data, type, full) {

						return '<div class="am-btn-toolbar">'
								+ ' <div class="am-btn-group am-btn-group-xs">'
								//+' <button  class="am-btn am-btn-default am-btn-xs am-text-success am-hide-sm-only" onclick="showModallist(\''
								//+ full.functionId
								//+ '\')" ><span class="am-icon-search"></span> 查看</button>'
								+ '  <button  class="am-btn am-btn-default am-btn-xs am-text-secondary" onclick="showModal(\''
								+ full.functionId
								+ '\')"><span class="am-icon-pencil-square-o"></span> 修改</button>'

								+ ' <button  class="am-btn am-btn-default am-btn-xs am-text-danger am-hide-sm-only" onclick="showConfirm(\''
								+ full.functionId
								+ '\')" ><span class="am-icon-trash-o"></span> 删除</button>'

								+ ' </div>' + ' </div>';
					}
				} ],

	});
}

function orderGroup() {
	$('#am_tab').on('click', 'tr.group', function() {
		var currentOrder = maintable.order()[0];
		console.info(currentOrder);
		if (currentOrder[0] === 2 && currentOrder[1] === 'asc') {
			maintable.order([ 2, 'desc' ]).draw();
		} else {
			maintable.order([ 2, 'asc' ]).draw();
		}
	});
}

/**
 * 添加或修改的模态窗口 type=1 添加 type=2 修改
 */
function showModal(id) {
	initOptions1();
	var $modal = $("#am_modal");
	var $title = $("#am_modal_title");
	if (id != undefined) {
		$title.html("<b>修改</b>");
		$modal.attr("type", 2);
		$("#functionId").val(id);
		// 隐藏functionId:因为让functionId为自增长默认给functionId的value=0用来跳过增加校验
		$("#functionId").show();
		var data = {
			functionId : id
		};
		var callback = function back(data) {
			console.info(data);
			$("#k").val(data.data[0]['k']);
			$("#functionUrl").val(data.data[0]['functionUrl']);
			$("#icon").val(data.data[0]['icon']);
			$("#functionName").val(data.data[0]['functionName']);
			$("#index").val(data.data[0]['index']);
			var type = data.data[0]['type'];
			if (type == 0) {
				$("#roleType1").uCheck('uncheck');
				$("#roleType0").uCheck('check'); 
				$("#roleFunctionUrlmodel").hide();
				$("#parentId_modal").hide();
			} else if (type == 1) {
				$("#roleType0").uCheck('uncheck');
				$("#roleType1").uCheck('check');
				$("#roleFunctionUrlmodel").show();
				$("#parentId_modal").show();

			}
			$("#roleType0").uCheck('disable');
			$("#roleType1").uCheck('disable');
			$("#parentId option[value='" + data.data[0]['parentId'] + "']").attr("selected", "selected");
		}
		var config = {
			url : urlConfig.getFunctionQuery,
			data : data,
			callback : callback
		};
		jqAjax(config);
	} else {
		$title.html("<b>添加</b>");
		$modal.attr("type", 1);
		$("#functionId").hide();
		$("#k").val("");
		$("#functionUrl").val("");
		$("#icon").val("");
		$("#functionName").val("");
		$("#index").val("");
		$("#parentId").val("");
		$("#roleType0").uCheck('enable');
		$("#roleType1").uCheck('enable');
	}
	$modal.modal();
	// 根据父子节点事件判断URL是否显示
	$('#roleType0').change(function() {
		var rankType = $("#roleType0").val();
		if (rankType == 0) {
			$("#roleFunctionUrlmodel").hide();
			$("#parentId_modal").hide();
		}
	})
	$('#roleType1').change(function() {
		var rankType = $("#roleType1").val();
		if (rankType == 1) {
			$("#roleFunctionUrlmodel").show();
			$("#parentId_modal").show();
		}
	})
}
/**
 * 初始化下拉列表(显示子父节点名称)
 */
function initOptions1() {
	var $parentFun = $("#parentId");
	var callback = function(data) {
		if (data && data.data) {
			var list = data.data;
			$parentFun.empty();
			for (var i = 0; i < list.length; i++) {
				var item = list[i];
				$parentFun.append("<option value='" + item.parentId + "'>" + item.child_parentName + "</option>");
			}
		}
		$parentFun.attr("state", 1);
	}
	var config = {
		url : urlConfig.getParentName,
		data : {},
		callback : callback
	};
	jqAjax(config);
}
/**
 * 提交表单
 */
function commitModal() {
	//表单验证补充（验证index为整数）
	var regex = /^\d+$/;
	if(!regex.test($("#index").val())){
		warning("index", "序号必须是非负整数！")
		return false;
	}
	
	var $modal = $("#am_modal");
	var k = $("#k").val();
	var functionName = $("#functionName").val();
	var functionId = $("#functionId").val();
	var commitType = $modal.attr("type");//提交类型，新增1,修改2
	var KData = {
		k : k,
		functionName :functionName,
		commitType,commitType,
		functionId,functionId
	};
	var callbackon = function back(data) {
		if(data.success==true){
			var url = urlConfig.addFunction;
			if (commitType == 2) {
				url = urlConfig.updateFunction;
			}
			var data = getFormDatas("#am_form");
			if (commitType != 2) {
				// 跳过functionId添加时候的验证
				delete data.functionId;
			}
			// 判断父子节点如果是父节点就删除判断 url校验为空 如字节点显示URL 并且校验有效！
			var rankType = $(".add_radio[type='radio']:checked").val();
			if (rankType == 0 && data.type == 0) {
				delete data.functionUrl;
				delete data.parentId;
			}
			var validator = validatorForm(data, $("#am_modal"));
			console.info(data);
			var config = {
				url : url,
				data : data,
				callback : callbackFun
			};
			if (validator) {
				jqAjax(config);
			}
		}else{
			alert(data.msg);
		}

	}
	var configUser = {
		url : urlConfig.getFunctionK,
		data : KData,
		callback : callbackon
	};
	jqAjax(configUser);
}

/**
 * 获取表单数据
 */
function getFormDatas(id) {
	var inputs = $(id).find("input,select");
	var data = {};
	for (var i = 0; i < inputs.length; i++) {
		var input = $(inputs[i]);
		var type = input.attr("type");
		if (type == 'hidden' || type == 'text' || type == 'password' || type == 'select') {
			var value = input.val();
			if (value instanceof Array) {
				value = value.join(",");
			}
			data[input.attr("id")] = value;
		} else if (type == 'radio') {
			var value = $("input[name='" + input.attr("name") + "']:checked") .val();
			data[input.attr("name")] = value;
		}
	}
	return data;
}

/**
 * 
 * 查看信息的模态窗口
 */
function showModallist(id) {
	var $modal = $("#am_modal_showlist");
	var data = {
		functionId : id
	};
	var callback = function back(data) {
		//$("#functionId_show").val(data.data[0]['functionId']);
		$("#k_show").val(data.data[0]['k']);
		$("#child_parentName").val(data.data[0]['child_parentName']);
		$("#functionUrl_show").val(data.data[0]['functionUrl']);
		$("#icon_show").val(data.data[0]['icon']);
		$("#functionName_show").val(data.data[0]['functionName']);
		$("#index_show").val(data.data[0]['index']);
		var type = data.data[0]['type'];
		if (type == 0) {
			$("#roleType0_show").attr("checked", "checked");
		} else {
			$("#roleType1_show").attr("checked", "checked");
		}
		// 下拉列表回显
		$("#actionId_show option[value='" + data.data[0]['actionId'] + "']").attr("selected", "selected");
	}
	var config = {
		url : urlConfig.getFunctionQuery,
		data : data,
		callback : callback
	}

	jqAjax(config);
	// 模态窗口的大小
	$modal.modal({
		width : 600,
		height : 720
	});
}

/**
 * 删除信息
 */
function showConfirm(id) {
	var $modal = $("#am_confirm");
	$("#functionId").val(id);
	$modal.modal({
		relatedTarget : this,
		onConfirm : function(options) {
			var id = $("#functionId").val();
			var data = {
				functionId : id
			};
			var config = {
				url : urlConfig.deleteFunction,
				data : data,
				callback : callbackFun
			};
			jqAjax(config);
		},
		onCancel : function() {
		}
	});
}

function callbackFun(data) {
	createTable();
	showAlertMsg(data.msg, "am_modal");
}
